import random

from django.http import HttpResponse
from django_redis import get_redis_connection
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

# from celery_tasks.sms.yuntongxun import CCP
from meiduo_mall.libs.captcha.captcha import captcha
from verfications.serializers import ImageCodeCheckSerializer
from . import constants
from celery_tasks.sms import tasks as sms_tasks


class ImageCodeView(APIView):

    def get(self,request, image_code_id):
        # 生成验证码图片
        text, image = captcha.generate_captcha()
        print('图片验证码%s' % text)
        # 连接redis
        redis_conn = get_redis_connection("verify_codes")
        # 将验证码真实值保存到redis
        redis_conn.setex("img_%s" % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)


        # 固定返回验证码图片数据，不需要REST framework框架的Response帮助我们决定返回响应数据的格式
        # 所以此处直接使用Django原生的HttpResponse即可
        return HttpResponse(image, content_type="image/jpg")


class SMSCodeView(GenericAPIView):
    """
    短信验证码
    """
    serializer_class = ImageCodeCheckSerializer

    def get(self,request, mobile):
        # t通过序列化器验证图片验证码
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)

        # 生成短信验证码
        sms_code = "%06d" % random.randint(0, 999999)
        print('短信验证码%s' % sms_code)

        # 保存短信验证码
        redis_conn = get_redis_connection("verify_codes")
        pl = redis_conn.pipeline()
        pl.setex("sms_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex("send_flag_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.execute()

        # 发送短信
        # sms_code_expires = str(constants.SMS_CODE_REDIS_EXPIRES // 60)
        # ccp = CCP()
        # ccp.send_template_sms(mobile, [sms_code, sms_code_expires], constants.SMS_CODE_TEMP_ID)
        # print(sms_code)


        sms_code_expires = str(constants.SMS_CODE_REDIS_EXPIRES // 60)
        sms_tasks.send_sms_code.delay(mobile, sms_code, sms_code_expires)

        # 返回成功信息
        return Response({"message": "OK"})